<template>
    <div class="common-page page-news-articles" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <!-- <comp-paths class="route" :paths="['/news', $route.fullPath]"></comp-paths> -->
            <div class="title">{{ $options.title }}</div>
        </div>
        <comp-articles class="common-page__body" ref="list" :type="type" select link>
            <template #head="scope">
                <el-button type="plain" size="small" icon="el-icon-refresh" @click="search()">刷新列表</el-button>
                <el-button type="primary" size="small" icon="el-icon-plus" @click="addArticle()">添加信息</el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" @click="delArticle(...scope.selects)">删除信息</el-button>
            </template>
            <template #body="scope">
                <el-button type="primary" size="mini" @click.stop="getArticle(scope.data)">详情</el-button>
                <el-button type="danger" size="mini" @click.stop="delArticle(scope.data)">删除</el-button>
            </template>
        </comp-articles>
        <comp-dialog title="添加信息" ref="article">
            <el-form size="small" label-width="98px" style="margin-right:20px" @submit.native.prevent v-if="article">
                <el-form-item label="信息封面：">
                    <img style="display: block; margin: 0 10px 10px 0; max-width: 120px; height: 60px" :src="article.banner.url" v-if="article.banner" />
                    <el-button type="plain" icon="el-icon-plus" @click="addArticle('upload-banner')">{{ article.banner ? "更换图片" : "选择图片" }}</el-button>
                </el-form-item>
                <el-form-item label="信息视频：">
                    <video style="display: block; margin: 0 10px 10px 0; width: 240px; height: 135px; background-color: black; object-fit: contain" :src="article.video.url" controls controlslist="nodownload noremoteplayback" preload="none" v-if="article.video"></video>
                    <el-button type="plain" icon="el-icon-plus" @click="addArticle('upload-video')">{{ article.video ? "更换视频" : "选择视频" }}</el-button>
                </el-form-item>
                <el-form-item label="信息标题：" required>
                    <el-input ref="articleTitle" type="textarea" v-model="article.title" style="width: 640px" placeholder="请输入" :maxlength="100" :rows="2" resize="none" :readonly="loading" @change="addArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="信息摘要：">
                    <el-input type="textarea" v-model="article.summary" style="width: 640px" placeholder="请输入" :maxlength="200" :rows="5" resize="none" :readonly="loading" @change="addArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="信息正文：">
                    <comp-html-editor ref="articleContentEditor"
                                      @uploadProgress="handleUploadProgress"
                                      style="width: 640px; height: 300px" editing :content="article.content"></comp-html-editor>
                </el-form-item>
                <el-form-item label="信息来源：">
                    <el-input v-model="article.referer" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="信息原文：">
                    <el-input v-model="article.source" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="信息作者：">
                    <el-input v-model="article.author" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="信息分类：">
                    <el-select v-model="article.tag.id" style="width: 640px" placeholder="请选择" @change="addArticle('validate')">
                        <el-option v-for="data in tags" :key="data.id" :label="data.name" :value="data.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="信息权重：">
                    <el-input v-model="article.weight" style="width: 640px" placeholder="请输入" :readonly="loading" @change="addArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="置顶：">
                    <el-checkbox v-model="article.isTop" style="width: 640px"
                                 :readonly="loading"
                                 true-label="1"
                                 false-label="0"
                                 @change="addArticle('validate')"></el-checkbox>
                </el-form-item>
                <el-form-item label="发布时间：" label-width="120px" required>
                    <el-date-picker type="datetime" v-model="article.publishTime" size="small" style="margin-right: 12px; width: 620px"  value-format="timestamp" placeholder="发布时间" />
                </el-form-item>
                <el-form-item label="信息状态：">
                    <el-select v-model="article.published" style="width: 640px" placeholder="请选择" @change="addArticle('validate')">
                        <el-option v-for="data in env.articlePublisheds" :key="data.id" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="addArticle('submit')">添加</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="addArticle('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="上传进度" ref="nProgress">
            <div style="height: 100px;width: 300px">
                <el-progress :percentage="uploadProgress"></el-progress>
            </div>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, toMagicImgURL, selectFile } from "../util";
    import env from "@/env";
    export default {
        name: "page-news-articles",
        title: "信息管理",
        nodes: ["/menu/news"],
        childs: ["news-article"],
        mixins: [mixin],
        data: () => ({
            loading: false,
            type: "news",
            article: null,
            tags: [],
            baseApiUrl:env.xhrPrefix,
            uploadProgress: 0,
        }),
        methods: {
            search() {
                if (this.loading) return;
                this.$nextTick(() => this.$refs.list.init());
            },
            addArticle(action, data) {
                if (this.loading) return;
                let form = this.article;
                if (!action || action === "start") {
                    this.loading = true;
                    this.plugins.user.getArticleOfTags({ linage: 100, page: 1 }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.tags = res.data.list.reduce((tags, tag) => {
                                let type = this.env.articleTypes.find((type) => type.value === this.type);
                                if (type && tag.tag.id === type.id) tags.push(tag);
                                return tags;
                            }, []);
                            this.article = this.plugins.user.formatArticle();
                            this.article.type = this.type;
                            this.article.startTime = this.startTime;
                            this.article.published = "not";
                            this.addArticle("validate");
                            this.$refs.article.init();
                            this.$nextTick(() => this.$refs.articleTitle.focus());
                            this.$nextTick(() => this.$refs.articleContentEditor.init());
                        } else {
                            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "validate") {
                    let error = "";
                    form.title = string(form.title).trim();
                    error = error || (form.title ? "" : "请输入信息标题！");
                    error = error || (form.publishTime ? "" : "请选择发布时间！");
                    form.summary = string(form.summary).trim();
                    form.content = string(() => this.$refs.articleContentEditor.getContent()) || string(form.content);
                    form.referer = string(form.referer).trim();
                    form.source = string(form.source).trim();
                    form.author = string(form.author).trim();
                    form.editor = string(form.editor).trim();
                    form.weight = Math.max(int(form.weight), 0) || null;
                    form.startTime = string(form.startTime)
                    form.published = form.published || this.env.articlePublisheds[0].value;
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "upload-banner") {
                    if (!data) return selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else this.addArticle(action, file);
                    });
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    this.loading = true;
                    this.plugins.user.uploadFile(data, "image", progress).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            form.banner = this.baseApiUrl+"/user/sysStorage/getFile/"+res.data.id+"?id="+res.data.id//toMagicImgURL(res.data.value, 120, 120);
                            this.addArticle("validate");
                        } else {
                            this.plugins.modal.alert("图片上传失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "upload-video") {
                    if (!data) return selectFile("video/*").then((file) => {
                        if (file.size > 5000 * 1048576) this.plugins.modal.toast("视频过大，不能大于5000MB哦！请重新选择。", "error");
                        else this.addArticle(action, file);
                    });
                    let timer = null;
                    this.loading = true;
                    this.plugins.user.uploadFile(data, "video", this.handleUploadProgress).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            form.video = this.baseApiUrl+"/user/sysStorage/getFile/"+res.data.id+"?id="+res.data.id //res.data.value;
                            this.addArticle("validate");
                        } else {
                            this.plugins.modal.alert("视频上传失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "submit") {
                    if (!this.addArticle("validate", true)) return;
                    this.loading = true;
                    if(form.isTop == null){
                        form.isTop = 0
                    }
                    this.plugins.user.addArticle(form).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("添加成功！", "success");
                            this.addArticle("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("添加失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.article.close();
                }
            },
            getArticle(article) {
                if (this.loading) return;
                this.$router.push("/news/article?articleId=" + article.id);
            },
            delArticle(...articles) {
                if (this.loading) return;
                if (articles.length === 0) return this.plugins.modal.toast("请先勾选要删除的信息哦！", "warning");
                let content = " <span style='color:red;'>" + (articles.length > 1 ? "勾选的" + articles.length + "篇信息" : articles[0].title) + "</span> 吗？";
                this.plugins.modal.alert("删除确认", "确定删除" + content, "warning", ["确定删除", "再想想"]).then((ok) => {
                    if (!ok) return;
                    this.loading = true;
                    this.plugins.user.delArticle(...articles).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("删除成功！", "success");
                            this.search();
                        } else {
                            this.plugins.modal.alert("删除失败", res.code + "：" + res.msg, "error");
                        }
                    });
                });
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                this.loading = true;
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.search();
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/home"));
                    }
                });
            },
            handleUploadProgress(e){
                console.log('上传进度edit',e)
                if(e.loaded && e.total){
                    this.$refs.nProgress.init()
                    this.uploadProgress = Math.round(e.loaded/e.total*100)
                    if(e.loaded == e.total){
                        this.nextTick(()=>{
                            this.$refs.nProgress.close()
                        })
                    }
                }else{
                    this.$refs.nProgress.close()
                }
            }
        },
    };
</script>

<style lang="scss">
    .page-news-articles {
        overflow: hidden;
    }
</style>
